package com.ant.backstage.biz.serviceImpl;

import com.ant.backstage.facade.ApiReturn;
import com.ant.backstage.facade.code.ApiReturnCode;
import com.ant.backstage.facade.request.CheckVerifyCodeRequest;
import com.ant.backstage.facade.request.GetVerificationCodeRequest;
import com.ant.backstage.facade.response.vo.GetVerificationCodeResponse;
import com.ant.backstage.facade.serviceInterface.VerficationFacadeService;
import com.ant.backstage.service.VerificationICodeService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @param $
 * @author zhangyu
 * @description $
 * @date $ $
 * @return $
 * @since
 **/
@Service("verficationFacadeService")
public class VerficationFacadeServiceImpl implements VerficationFacadeService {
    private static Logger logger = LogManager.getLogger(VerficationFacadeServiceImpl.class);

    @Resource
    VerificationICodeService verificationICodeService;

    /**
     * 异常信息：
     * java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
     *
     * 错误原因大致是因为主线程完成后，子线程不能获取request请求信息，包括session等导致此错误。
     * 在网上找的一片文章参考，只要在开启新线程前添加如下，让子线程共享主线程servletRequestAttributes即可，亲测可用。
     *
     * ServletRequestAttributes servletRequestAttributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
     * RequestContextHolder.setRequestAttributes(servletRequestAttributes,true);//设置子线程共享
     *
     **/
    /**
     *  Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
     *
     *
     *
     **/


    @Override
    public ApiReturn getVerificationCode(GetVerificationCodeRequest getRequest) {
        ApiReturn apiReturn = verificationICodeService.getVerificationCode(getRequest);
        if (apiReturn.getCode().equals(ApiReturnCode.SUCCESSFUL.getCode())) {
            Map data = (Map) apiReturn.getData();
            GetVerificationCodeResponse response = new GetVerificationCodeResponse();
            String verifyCode = data.get("verifyCode").toString();
            response.setVerifyCode(verifyCode);
            apiReturn.setData(response);
        }
        return apiReturn;
    }

    @Override
    public ApiReturn checkVerificationCode(CheckVerifyCodeRequest checkVerifyCodeRequest) {
        ApiReturn apiReturn = verificationICodeService.checkVerificationCode(checkVerifyCodeRequest, null);
        return apiReturn;
    }

}
